package com.aorise.controller.system;

import com.aorise.exception.DataValidationException;
import com.aorise.exception.SystemException;
import com.aorise.model.request.AddRoleReq;
import com.aorise.model.request.UpdateRoleReq;
import com.aorise.model.response.RoleInfoRes;
import com.aorise.model.system.Authority;
import com.aorise.service.system.AuthorityService;
import com.aorise.service.system.RoleService;
import com.aorise.utils.DataValidation;
import com.aorise.utils.Page;
import com.aorise.utils.StatusDefine;
import com.aorise.utils.StatusDefineMessage;
import com.aorise.utils.json.JsonResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @Auther: zhouhao
 * @Date: 2019/5/27
 * @Description:
 */
@Slf4j
@Api(description = "角色相关接口")
@RestController
@Validated
@RequestMapping("api/role")
public class RoleController {

    @Autowired
    RoleService roleService;

    @Autowired
    AuthorityService authorityService;


    /**
     * 获取权限列表
     * HTTP 方式：GET
     * API 路径：/api/role/
     * 方法名：allPermission
     * 方法返回类型：String
     */
    @ApiOperation(value = "获取权限列表", httpMethod = "GET", response = String.class, notes = "获取权限列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "token", value = "token",  paramType = "query", dataType = "string")
    })
    @RequiresPermissions("JSQXGL")
    @RequestMapping(value = "/allPermission", method = RequestMethod.GET,produces="application/json")
    public String allPermission(String token){
        List<Authority> authorities =null;
        try {
            authorities = authorityService.allPermission();
        }catch (DataValidationException e) {
            log.error(
                    "controller:RoleController. function:allPermission...msg: allPermission DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:RoleController. function:allPermission...msg: allPermission DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:RoleController. function:allPermission. msg:allPermission Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofSuccess(authorities);
    }

    /**
     * 添加角色
     * HTTP 方式：POST
     * API 路径：/api/role/
     * 方法名：addRole
     * 方法返回类型：String
     */
    @RequiresPermissions("JSQXGL")
    @ApiOperation(value = "添加角色", httpMethod = "POST", response = String.class, notes = "添加角色")
    @RequestMapping(value = "/addRole", method = RequestMethod.POST,produces="application/json")
    public String addRole(@RequestBody @Validated AddRoleReq addRoleReq, BindingResult result){
        try {
            if (result.hasErrors()) {
                return JsonResponseData.ofMessage(StatusDefine.DATA_FORMAT_ERROR, result.getFieldError().getDefaultMessage());
            }
            if(roleService.addRole(addRoleReq.getRoleName(),addRoleReq.getPermissions())){
                return JsonResponseData.ofSuccess(null);
            }
        }catch (SystemException e) {
            log.error(
                    "controller:RoleController. function:addRole...msg: addRole SystemException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        } catch (DataValidationException e) {
            log.error(
                    "controller:RoleController. function:addRole...msg: addRole DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:RoleController. function:addRole...msg: addRole DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:RoleController. function:addRole. msg:addRole Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofFailure();
    }

    /**
     * 所有角色
     * HTTP 方式：GET
     * API 路径：/api/role/
     * 方法名：allRole
     * 方法返回类型：String
     */
    @ApiOperation(value = "所有角色", httpMethod = "GET", response = String.class, notes = "所有角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token",  paramType = "query", dataType = "string")

    })
    @RequestMapping(value = "/allRole", method = RequestMethod.GET,produces="application/json")
    public String allRole(String token){
        List<RoleInfoRes> roles =null;
        try {
            roles = roleService.selectAllRole();
        }catch (DataValidationException e) {
            log.error(
                    "controller:RoleController. function:allRole...msg: allRole DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:RoleController. function:allRole...msg: allRole DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:RoleController. function:allRole. msg:allRole Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofSuccess(roles);
    }

    /**
     * 分页所有角色列表
     * HTTP 方式：GET
     * API 路径：/api/role/
     * 方法名：allRole
     * 方法返回类型：String
     */
    @ApiOperation(value = "分页所有角色列表", httpMethod = "GET", response = String.class, notes = "分页所有角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleName", value = "角色名",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageSize", value = "每页的数量",  paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "pageNum", value = "当前页",  paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "token", value = "token",  paramType = "query", dataType = "string")

    })
    @RequiresPermissions("JSQXGL")
    @RequestMapping(value = "/selectPageRole", method = RequestMethod.GET,produces="application/json")
    public String selectPageRole(String roleName,Integer pageSize, Integer pageNum, String token){
        Page page =null;
        DataValidation validation = new DataValidation();
        try {
            validation.chkLength(roleName,0,20,"角色名不能超过20个字符");
            page = roleService.selectPageRole(roleName, pageSize, pageNum);
        }catch (DataValidationException e) {
            log.error(
                    "controller:RoleController. function:selectPageRole...msg: selectPageRole DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:RoleController. function:selectPageRole...msg: selectPageRole DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:RoleController. function:selectPageRole. msg:selectPageRole Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofSuccess(page);
    }

    /**
     * 删除角色
     * HTTP 方式：GET
     * API 路径：/api/role/
     * 方法名：delRole
     * 方法返回类型：String
     */
    @ApiOperation(value = "删除角色", httpMethod = "DELETE", response = String.class, notes = "删除角色")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "roleId", value = "角色ID",  paramType = "query", dataType = "int"),
        @ApiImplicitParam(name = "token", value = "token",  paramType = "query", dataType = "string")

    })
    @RequiresPermissions("JSQXGL")
    @RequestMapping(value = "/delRole", method = RequestMethod.DELETE,produces="application/json")
    public String delRole(Integer roleId,String token){
        try {
            if(roleId == null){
                throw new DataValidationException("角色ID不能为空");
            }
            if(roleService.delRole(roleId)){
                return JsonResponseData.ofSuccess(null);
            }
        }catch (DataValidationException e) {
            log.error(
                    "controller:RoleController. function:delRole...msg: delRole DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:RoleController. function:delRole...msg: delRole DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:RoleController. function:delRole. msg:delRole Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofFailure();
    }

    /**
     * 编辑角色
     * HTTP 方式：GET
     * API 路径：/api/role/
     * 方法名：updateRole
     * 方法返回类型：String
     */
    @RequiresPermissions("JSQXGL")
    @ApiOperation(value = "编辑角色", httpMethod = "POST", response = String.class, notes = "编辑角色")
    @RequestMapping(value = "/updateRole", method = RequestMethod.POST,produces="application/json")
    public String updateRole(@RequestBody @Validated UpdateRoleReq updateRoleReq,BindingResult result){
        try {
            if (result.hasErrors()) {
                return JsonResponseData.ofMessage(StatusDefine.DATA_FORMAT_ERROR, result.getFieldError().getDefaultMessage());
            }
            if(roleService.updateRole(updateRoleReq)){
                return JsonResponseData.ofSuccess(null);
            }
        }catch (SystemException e) {
            log.error(
                    "controller:RoleController. function:updateRole...msg: updateRole SystemException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataValidationException e) {
            log.error(
                    "controller:RoleController. function:updateRole...msg: updateRole DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:RoleController. function:updateRole...msg: updateRole DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:RoleController. function:updateRole. msg:updateRole Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofFailure();
    }

    @ApiOperation(value = "查看角色", httpMethod = "GET", response = String.class, notes = "查看角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID",  paramType = "query", dataType = "int")
    })
    @RequiresPermissions("JSQXGL")
    @RequestMapping(value = "/selectRole", method = RequestMethod.GET,produces="application/json")
    public String selectRole(Integer roleId){
        List<Authority> authorities =null;
        try{
            if (roleId == null) {
                throw new DataValidationException("角色ID不能为空");
            }
            authorities = authorityService.selectByRoleId(roleId);
        }catch (DataValidationException e) {
            log.error(
                    "controller:RoleController. function:selectRole...msg: selectRole DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:RoleController. function:selectRole...msg: selectRole DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:RoleController. function:selectRole. msg:selectRole Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofSuccess(authorities);
    }
}
